<template>
  <div class="recursion">
    <el-checkbox-group v-model="value" @change="(val) => valueChange(val)">
      <ul style="padding: 0">
        <li v-for="menu in list" :key="menu.id">
          <el-checkbox :label="menu.value">{{ menu.title }}</el-checkbox>
          <el-button v-if="menu.hasChildren" @click="selectAll(menu)" type="text">全 选</el-button>
          <item v-if="menu.hasChildren" :list="menu.children" @change="handleItemChange" :value="value"></item>
        </li>
      </ul>
    </el-checkbox-group>
  </div>
</template>
<script>
import item from "./item.vue"

export default {
  components: {
    item,
  },
  model: {
    props: "value",
    event: "change",
  },
  props: {
    list: [],
    value: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {}
  },
  methods: {
    recursion(list) {
      let ids = []
      if (list.length > 0) {
        list.forEach((v) => {
          ids.push(v.value)
          if (v.hasChildren) {
            ids = ids.concat(this.recursion(v.children))
          }
        })
      }
      return ids
    },
    selectAll(menu) {
      if (!this.value.includes(menu.value)) {
        // 选中
        if (menu.hasChildren) {
          let ids = []
          ids = this.recursion(menu.children)
          ids.push(menu.value)
          ids = Array.from(new Set(this.value.concat(ids)))
          this.$emit("change", ids)
        }
      } else {
        // 反选
        if (menu.hasChildren) {
          let ids = []
          ids = this.recursion(menu.children)
          ids.push(menu.value)
          ids = this.value.filter((v) => !ids.includes(v))
          this.$emit("change", ids)
        }
      }
    },
    handleItemChange(ids) {
      this.$emit("change", ids)
    },
    valueChange(val) {
      this.$emit("change", val)
    },
  },
}
</script>
